import dayjs from "dayjs";
import moment from "moment";
let isSameOrBefore = require("dayjs/plugin/isSameOrBefore");
dayjs.extend(isSameOrBefore);
export const calculate = (res, dateString) => {
  let startTime = dateString + " " + res.startTime;
  let endTime = dateString + " " + res.endTime;
  let objList: any = splitTimeToBlock(startTime, endTime);
  if (res.useableTimeConfig == "1") {
    objList.map((item) => {
      item.status = 1;
    });
  }
  if (res.useableTimeConfig == "2" && res.euseVipcardUseableTimeConfigList) {
    if (res.euseVipcardUseableTimeConfigList.length > 0) {
      let arr = [];
      res.euseVipcardUseableTimeConfigList.map((item) => {
        arr.push(...splitTimeToBlock(item.startTime, item.endTime, true));
      });
      arr = arr.sort(function (a, b) {
        return dayjs(a.time) - dayjs(b.time);
      });
      objList = calcStatus(arr, objList, 1);
    }
  }
  if (res.euseUserBookRecordList && res.euseUserBookRecordList.length > 0) {
    let arr: any = [];
    res.euseUserBookRecordList.map((item) => {
      arr.push(...splitTimeToBlock(item.bookStartTime, item.bookEndTime, true));
    });
    arr = arr.sort(function (a, b) {
      return moment(a.time) - moment(b.time);
    });
    objList = calcStatus(arr, objList, 2);
  }
  if (res.venueHolidayList && res.venueHolidayList.length > 0) {
    let arr: any = [];
    res.venueHolidayList.map((item) => {
      arr.push(...splitTimeToBlock(item.startTime, item.endTime, true));
    });
    arr = arr.sort(function (a, b) {
      return moment(a.time) - moment(b.time);
    });
    objList = calcStatus(arr, objList, 3, true);
  }
  if (res.useableTimeConfig == "2" && res.euseVipcardUseableTimeConfigList) {
    if (res.euseVipcardUseableTimeConfigList.length == 0) {
      objList.map((item) => {
        item.status = 4;
      });
    }
  }
  objList.map((item) => {
    if (moment(new Date()).diff(moment(item.time), "minute") > 0) {
      item.status = 0;
    }
  });
  return objList;
};

//status 0过期 1可用 2被约 3休息 4限定
export const calcStatus = (arr, date, status) => {
  let statusList = {
    0: "过期",
    1: "可用",
    2: "被约",
    3: "休息",
    4: "限定",
  };
  //console.log(arr, date, statusList[status], "_date");
  date.map((item) => {
    let hasCheckIndex = arr.findIndex((e) => {
      return e.time == item.time;
    });
    if (hasCheckIndex > -1) {
      item.status = status;
    }
  });
  return date;
};

//时间段分割
export const splitTimeToBlock = (startDate, endDate, need?) => {
  var start = dayjs(startDate);
  let list: any = [];
  let timeValue: any = "";
  while (start.isSameOrBefore(endDate, "m")) {
    timeValue = start.format("HH:mm");
    if (timeValue != undefined) {
      list.push({ time: start.format("YYYY-MM-DD HH:mm:ss"), status: 4 });
    }
    let newDate = start.add(15, "m");
    list.push(newDate);
    start = newDate;
  }
  list = list.filter((e) => e.time != undefined);
  if (need) {
    list.pop();
  }
  return list;
};
